<template>
  <x-main>
    <x-table ref="table" :isPage="true" :optionWidth="180" rowKey="userId" @search="onSearch" @modify="onModify" @reset="resetPwd" @assignRole="onAssignRole" @remove="onRemove">
      <template v-slot:btn-tool>
        <el-button type="primary" @click="onAdd">新增</el-button>
      </template>
      <template #role="scope">
        <el-tag style="margin-right: 5px" v-for="(item, index) in scope.data.roleList" :key="index">{{ item.roleName }}</el-tag>
      </template>
      <template #status="scope">
        <el-switch @click="onClick(scope.data)" v-model="scope.data.lockFlag" active-value="0" inactive-value="1"></el-switch>
      </template>
    </x-table>
  </x-main>
</template>

<script setup name="sys-user-index">
import useStore from '@/stores/modules/sys/user';
const users = useStore();

import XForm from './Form.vue';
import XPwd from "./Pwd.vue";
import XRole from "./Role.vue";

import {onMounted, ref} from "vue";

onMounted(() => {
  users.init(table)
  users.getList(1, 10);
})

let table = ref();

/**
 * 搜索
 * @param pageNo
 * @param pageSize
 * @param condition
 */
const onSearch = (pageNo, pageSize, condition) => {
  users.getList(pageNo, pageSize, condition);
}

/**
 * 状态切换
 * @param row
 */
const onClick = (row) => {
  let status = row.status
  let msg = status == 1 ? "是否禁用该用户" : "是否启用该用户"

  Msg.confirm(msg).then(async _ => {
    delete row.password;
    let success = await users.modify(row);
    if (! success) {
      row.status = row.status == 0 ? 1 : 0;
    }
  }).catch(err => {
    row.status = row.status == 0 ? 1 : 0;
  })
}

/**
 * 新增
 * @returns {Promise<void>}
 */
const onAdd = async () => {
  open(XForm, "添加用户", {}, 900)
}

/**
 * 修改
 * @param row
 * @returns {Promise<void>}
 */
const onModify = async (row) => {
  let info = await users.getInfo(row.id);
  if (! info) {
    return
  }

  let roles = info.roleList;
  if(! Helper.emptyArray(roles)) {
    info.role = roles.map(x => {return x.roleId});
  }

  open(XForm, "修改用户", info, 900)
}

/**
 * 重置密码
 * @param row
 * @returns {Promise<void>}
 */
const resetPwd = async (row) => {
  open(XPwd, "重置密码", row, 450)
}

/**
 * 分配角色
 * @param row
 */
const onAssignRole = async (row) => {
  let info = await users.getInfo(row.id);
  if (! info) {
    return
  }

  open(XRole, "分配角色", info, 800)
}

/**
 * 删除
 * @param row
 */
const onRemove = (row) => {
  Msg.confirm("确认删除该数据？").then(_ => {
    users.remove(row.id)
  })
}

const open = (component, title, data, width) => {
  const op = Dialog.open(component, title)
  op.setWidth(width)

  op.mounted(c => {
    c.render(data)
  })

  op.confirm(c => {
    c.submit()
  })
}
</script>
